package com.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

public class HibernateUtil {
	private static Session session;
	private static SessionFactory sessionFactory;
	private static Transaction transaction;
	
	public static Session getSession() {
		if(session==null){
			ouvrirSession();
		}
		return session;
	}
	
	public static SessionFactory getSessionFactory() {
		if(sessionFactory==null)
			ouvrirSession();
		return sessionFactory;
	}
	
	public static Transaction getTransaction(){
		System.out.println(transaction.isActive());
		if(session==null)
			ouvrirSession();
		transaction = session.getTransaction();
		if(!transaction.isActive())
			transaction = session.beginTransaction();
		return transaction;
	} 
	
	private static void ouvrirSession(){
		try {
			/*Configuration config = new Configuration();
			config.configure();
			System.out.println();
			//SessionFactory factory = config.buildSessionFactory();
			ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
			sessionFactory = config.buildSessionFactory(sr);*/
			sessionFactory = new
					Configuration().configure().buildSessionFactory();

			/*sessionFactory = (SessionFactory) new InitialContext()
			.lookup("SessionFactory");
			session = sessionFactory.getCurrentSession();
			transaction = session.beginTransaction();*/

			session= sessionFactory.openSession();
			transaction = session.beginTransaction();
		} catch (Exception e) {
			// TODO: handle exception
			session=null;
			sessionFactory=null;
			System.out.println(e.getMessage());
		}
	}
}
